package com.toolsder.demo.spring.security.jwt.controller;

import com.google.common.base.Strings;
import com.toolsder.demo.spring.security.jwt.annotation.RoleMsg;
import com.toolsder.demo.spring.security.jwt.annotation.SystemRole;
import com.toolsder.demo.spring.security.jwt.config.util.JwtTokenUtil;
import com.toolsder.demo.spring.security.jwt.entity.JsonResult;
import com.toolsder.demo.spring.security.jwt.entity.UserInfo;
import com.toolsder.demo.spring.security.jwt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class JwtAuthController {


    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * jwt验证登陆
     */
    @PostMapping(value = "/authentication")
    public JsonResult<String> authentication(String username, String password) {
        if (Strings.isNullOrEmpty(username) || Strings.isNullOrEmpty(password)) {
            return JsonResult.error("用户名或者密码不能为空");
        }
        return JsonResult.success(userService.login(username, password));
    }

    @GetMapping(value = "/userInfo", name = "通过token获取用户信息")
    @SystemRole(roleMsg = @RoleMsg(code = "BASE", name = "基础权限", descpt = "所有用户都所具备的基础权限"))
    public JsonResult<UserInfo> userInfo(@RequestHeader("${jwt.header}") String token) {
        UserInfo userInfo = userService.getUserInfo(token);
        JsonResult<UserInfo> jsonResult = new JsonResult<>();
        return jsonResult.success(userInfo);
    }

    @GetMapping(value = "/refreshToken", name = "刷新token")
    @SystemRole(roleMsg = @RoleMsg(code = "BASE", name = "基础权限", descpt = "所有用户都所具备的基础权限"))
    public JsonResult<String> refresh(@RequestHeader("${jwt.header}") String token) {
        if (!jwtTokenUtil.isTokenExpired(token)) {
            return JsonResult.success(jwtTokenUtil.refreshToken(token));
        }
        return JsonResult.error("token刷新失败");
    }

    @PostMapping(value = "/modifyPassword", name = "修改个人密码")
    @SystemRole(roleMsg = @RoleMsg(code = "BASE", name = "基础权限", descpt = "所有用户都所具备的基础权限"))
    public JsonResult<String> modifyPassword(@RequestHeader("${jwt.header}") String token, String oldPassword, String password) {
        userService.modifyPassword(token, oldPassword, password);
        return JsonResult.success();
    }


}
